package com.zhiqingchun.common;

import java.util.List;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class JdbcBaseDao extends JdbcDaoSupport implements IJdbcBaseDao {

	@Override
	public List findPageList(String sql, Object[] args, Page page) {
		StringBuilder sql4count = new StringBuilder(300);
		if (page != null) {
			int sqlFrom = sql.toLowerCase().indexOf("from");
			sql4count.append("select count(1) ").append(sql.substring(sqlFrom));
//			sql4count.append("select count(1) from (");
//			sql4count.append(sql);
//			sql4count.append(")");
			page.setRecordCount(this.queryForInt(sql4count.toString(), args));
			sql = this.getSQL(sql, page);
		}
		return this.getJdbcTemplate().queryForList(sql, args);
	}
	
	private String getSQL(String sql, Page page) {
		//注意貌似oracle的startRow一般要加1，而mysql不用，mysql的记录行数是从0开始的
		int startRow = (page.getPageIndex() - 1) * page.getPageNumber();
		String _sql = new StringBuilder(sql).append(" limit ").append(page.getPageNumber()).append(" offset ").append(startRow).toString();
		return _sql;
	}
	
	public int queryForInt(String sql, Object[] args) {
		int count = getJdbcTemplate().queryForInt(sql.toString(), args);
		return count;
	}

}
